package rsexplorer.rstree;

import java.lang.reflect.Field;
import rsexplorer.utils.FieldFilter;
import java.lang.reflect.Modifier;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class ClassTreeNode extends FieldContainerTreeNode {

    protected Class<?> cls;

    public ClassTreeNode(Class<?> cls) {
        this(cls, null);
    }

    public ClassTreeNode(Class<?> cls, FieldFilter filter) {
        super(cls.getName(), null, filter, 0);
        this.cls = cls;

        init();
    }

    public Class<?> getClassObject() {
        return cls;
    }

    public void init() {
        try {
            removeAllChildren();
            Field[] fields = cls.getDeclaredFields();

            for (Field f : fields) {
                f.setAccessible(true);

                if (!Modifier.isStatic(f.getModifiers()))
                    continue;

                if (shouldFilterField(f))
                    continue;

                Object container = f.get(null);

                if (container == null)
                    container = "null";

                addChildField(f, container);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Object userObject, Object fieldObject) {
        try {
            //removeAllChildren();
            Field[] fields = cls.getDeclaredFields();

            int i = 0;
            for (Field f : fields) {

                f.setAccessible(true);

                if (!Modifier.isStatic(f.getModifiers()))
                    continue;

                Object container = f.get(null);

                if (container == null) {
                    container = "null";
                }

                updateChildField(i, f, container);
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
